<?php

class Controller_Commerce extends Controller_Website
{
	public function before()
	{
		parent::before();
		//$this->template->footer = Model::factory('directory')->getItemByToken('x22', 'footer');
		$this->db = Database::instance();
		$this->model = Model::factory('cart');
		$this->mod = Model::factory('directory');
        $this->man = Model::factory('manager');
		$this->section = 'viewcart';
		$this->template->description = $this->settings['description'];
		$this->template->keywords = $this->settings['keywords'];
		if (!isset($_SESSION)) {
			session_start();
		}
		$this->delivery = (isset($_SESSION['cartDelivery']) ? $_SESSION['cartDelivery'] : false);
		$this->discount = (isset($_SESSION['cartDiscount']) ? $_SESSION['cartDiscount'] : false);

		$this->template->footer = Model::factory('directory')->getItemByToken('rxx', 'footer');

//		$this->addScript('/scripts/fancybox/jquery.fancybox.pack.js');
//		$this->addScript('/scripts/plugin/gallery.js');
//		$this->addStyle('/styles/fancybox/jquery.fancybox.css');
//		$this->addScript('/cart/js/cart/');
//		$this->addStyle('/styles/cusel.css');
//		$this->addScript('/scripts/cusel-min-2.5.js');
//		$this->addScript('/scripts/loadSelect.js');

        //cusel
        $this->addScript('/scripts/cusel/jquery-1.6.1.min.js');
        $this->addScript('/scripts/cusel/cusel-min-2.5.js');
        $this->addStyle('/styles/cusel/cusel.css');

	}
        public function actionDeleteItem($section, $id)
	{
		if (isset($_SESSION['cart'][$section]) ? count($_SESSION['cart'][$section]) : false) {
			foreach ($_SESSION['cart'][$section] as $k => $v) {
				if ($v['id'] == $id) {
					unset($_SESSION['cart'][$section][$k]);
				}
			}
		}
		$this->response->redirect(Request::$controller . 'checkout/');
	}
        
	public function actionCheckout()
	{
		$this->template->title = 'Checkout';
		$orderItems = array();
		$sections = Cart::instance()->sections;
		$items = array();
		if (isset($_SESSION['cart']) ? count($_SESSION['cart']) : false) {
			foreach ($_SESSION['cart'] as $section => $cartItems) {
				foreach ($cartItems as $cartItem) {
					if (isset($sections[$section])) {
						$items[] = array_merge(array('source' => $sections[$section]['source']), $cartItem);
					}
				}
			}
		}
		if (isset($_POST['cart']) ? count($_POST['cart']) : false) {
			$_SESSION['cart'] = $_POST['cart'];
			$this->response->redirect(Request::$uri);
		}
		foreach ($items as $item) {
			try {
				$class = new ReflectionClass(ucfirst($item['source']) == 'Directory' ? 'DirectoryClass' : ucfirst($item['source']));
				$controller = $class->newInstance();
				if ($class->getMethod('validateItem')) {
					if (false !== ($result = $controller->validateItem($item))) {
						$orderItems[] = array_merge(array('source' => $item['source'], 'quantity' => $item['quantity'], 'token' => $item['token'],'text' => $item['text'],'color' =>$item['settings']['color'],'size' =>$item['settings']['size']), $result);
					}
				}
			} catch (ReflectionException $e) {
				continue;
			}
		}
		$isDigital = true;
		if (count($orderItems)) {
			foreach ($orderItems as $orderItem) {
				$isDigital &= $sections[$orderItem['section']]['isDigital'];
			}
			$this->template->content = new View('checkout');

			if (isset($this->settings['delivery'])) {
				$this->template->content->delivery = $this->settings['delivery'];
			}
			$this->template->content->items = $orderItems;
			//$this->template->content->form = $form;
						$form = new Form('payment');
			$form->hidden('delivery', 0);
			$form->radio('method', array('creditcard' => '', 'paypal' => ''))->required();
			$form->submit('submit', 'Go');
			$this->template->content->form = $form;
			if (Request::$method == 'POST') {
				if ($form->validate()) {
					$values = $form->getValues();
					if ($values['delivery']) {
						$_SESSION['cartDelivery'] = $values['delivery'];
					} else {
						$_SESSION['cartDelivery'] = false;
					}
					if ($values['method'] == 'creditcard') {
						$this->response->redirect(Request::$controller . 'creditcard/');
					} elseif ($values['method'] == 'paypal') {
						$this->response->redirect(Request::$controller . 'gopaypal/');
					}
				}
			}
		} else {
		    $this->template->content = new View('checkout');
			//$this->template->content = '<span id="heighter"></span>Your cart is empty';
		}
	}

	public function actionConfirmation($result = 'ok')
	{
		$this->template->title = 'Checkout';
		if ($result == 'ok') {
			$this->template->content = 'Thank you.';
		} elseif ($result == 'cancel') {
			$this->template->content = 'Try next time. Thank you.';
		}
	}


	public function actionIpn()
	{
		$this->autoRender = false;
		if ($orderId = $this->validateIpn()) {
			Cart::instance()->setPaid($orderId);
			$this->response->body = 'Payment done';
		} else {
			$this->response->body = 'Payment failed';
		}
	}

	private function log($message, $success = true, $end = false)
	{
		$text = '['.date('m/d/Y g:i A').'] - ' . (($success) ? 'SUCCESS: ' : 'FAILURE: ') . $message . "\n";
		if ($end) {
			$text .= "\n------------------------------------------------------------------\n\n";
		}
		if (!file_exists('_logs/ipn.txt')) {
			file_put_contents('_logs/ipn.txt', '');
		}
		$fp=fopen('_logs/ipn.txt', 'a');
		fwrite($fp, $text);
		fclose($fp);
	}

	private function validateIpn()
	{
		$ipnData = '';
		$ipnResponse = '';
		$this->log('Paypal IPN Intiated by ' . $_SERVER['REMOTE_ADDR'], true);
		if ($this->settings['sandbox']) {
			$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
		} else {
			$url = 'https://www.paypal.com/cgi-bin/webscr';
		}
		$post = '';
		foreach ($_POST as $k => $v) {
			$ipnData[$k] = $v;
			$post .= $k . '=' . urlencode($v) . '&';
		}
		if (isset($ipnData['txn_type']) ? $ipnData['txn_type'] == 'subscr_signup' : false) {
			$this->log('Subscription sign up.', true, true);
			return false;
		}

		$this->log('Post string: ' . $post, true);
		$post .= 'cmd=_notify-validate';

		$itemNumber = (isset($ipnData['item_number']) ? $ipnData['item_number'] : (isset($ipnData['item_number1']) ? $ipnData['item_number1'] : (isset($ipnData['invoice']) ? $ipnData['invoice'] : '')));
		if (!$itemNumber) {
			$this->log('Invalid IPN request.', false, true);
			return false;
		}
		if (!($order = $this->model->getOrderByToken($itemNumber))) {
			$this->log('Invalid order id.', false, true);
			return false;
		}
		$this->log('Order ID: ' . $order['id'], true);
		if ($this->settings['paypalEmail'] != $ipnData['receiver_email']) {
			$this->log('Invalid reciever email.', false, true);
			return false;
		}
		$gross = (isset($ipnData['mc_gross']) ? $ipnData['mc_gross'] : (isset($ipnData['mc_gross_1']) ? $ipnData['mc_gross_1'] : (isset($ipnData['payment_gross']) ? $ipnData['payment_gross'] : 0)));
		if ($order['delivery']) {
			$order['amount'] += $this->settings['delivery'];
		}
		if ($order['amount'] != $gross || 'USD' != $ipnData['mc_currency']) {
			$this->log('Currency: ' . $ipnData['mc_currency'], true);
			$this->log('Invalid amount. It had to be ' . $order['amount'] . ', but got ' . $gross . ' from IPN.', false, true);
			return false;
		}
		$curl = curl_init($url);
		curl_setopt ($curl, CURLOPT_HEADER, 0);
		curl_setopt ($curl, CURLOPT_POST, 1);
		curl_setopt ($curl, CURLOPT_POSTFIELDS, $post);
		curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, 1);
		$ipnResponse = curl_exec ($curl);
		curl_close ($curl);
		$this->log('Connection to ' . $url . ' successfuly completed.', true);
		$this->log('IPN response: ' . $ipnResponse, true);
		if (substr_count('VERIFIED', $ipnResponse)) {
			$this->log('IPN successfully verified. Order id is ' . $order['id'] . '.', true, true);
			return $order['id'];
		} else {
			$this->log('IPN validation failed.', false, true);
			return false;
		}
	}

		public function actionCreditCard()
	{
//		if (!$this->settings['isSandbox']) {
//			if (Request::$protocol != 'https') {
//				$this->response->redirect(Url::site(Request::$uri, 'https'));
//			}
//		}
		
		$this->template->title = 'Pay with credit card';
		$this->template->content = new View('payment/creditcard');
		$this->addStyle('/styles/autoform.css');
		$form = new Form('payment');
		//$form->template = 'payment/creditcard-form';
		$form->labelWidth = '150px';
		$form->fieldset('customer');
		$form->text('customerCustomer', 'Full name')->rule('required')->attribute('size', 40);
		$form->text('customerEmail', 'Email')->rule('required')->rule('email')->attribute('size', 40);
		$form->text('customerAddress', 'Address')->rule('required')->attribute('size', 40);
		$form->text('customerCity', 'City')->rule('required')->attribute('size', 40);
		$form->select('customerState', array_merge(array('' => ''), Text::$states), 'State')->rule('required');
		$form->text('customerZip', 'ZIP-code')->rule('required')->attribute('size', 10)->rule('integer')->rule('minLength', 5);
		$form->text('customerPhone', 'Phone')->attribute('size', 40);
		$form->textarea('customerComment', 'Comments')->attribute('cols', 25)->attribute('rows', 10);
		//$form->html('creditCardInfo', '', '<strong>Credit card information</strong>')->phantom()->bunched();
		$form->fieldset('creditcard');
		$form->select('creditCardType', array(
			'visa' => 'VISA',
			'mastercard' => 'Mastercard',
			'discover' => 'Discover',
			'amex' => 'American Express',
		), 'Card type');
		$form->text('acct', 'Card number')->rule('maxLength', 19)->attribute('size', 21)->rule('required');
		$form->text('firstName', 'First name')->rule('required');
		$form->text('lastName', 'Last name')->rule('required');
		$form->text('expMonth', 'Expiration month')->rule('minLength', 2)->rule('maxLength', 2)->rule('integer')->attribute('size', 2)->rule('required');
		$form->text('expYear', 'Expiration year')->rule('minLength', 4)->rule('maxLength', 4)->rule('integer')->attribute('size', 4)->rule('required');
		$form->text('cvv2', 'CSC')->attribute('size', 5)->rule('required');
		$form->textarea('street', 'Address')->attribute('cols', 25)->attribute('rows', 3)->rule('required');
		$form->text('city', 'City')->rule('required');
		$form->select('state', array_merge(array('' => ''), Text::$states), 'State')->rule('required');
		$form->text('zip', 'ZIP code')->attribute('size', 7)->rule('maxLength', 5)->rule('required');
		if ($this->settings['isSandbox']) {
			$form->elements['creditCardType']->value = 'visa';
			$form->elements['acct']->value = '4334981618387435';
			$form->elements['firstName']->value = 'Test';
			$form->elements['lastName']->value = 'User';
			$form->elements['expMonth']->value = '01';
			$form->elements['expYear']->value = '2015';
			$form->elements['cvv2']->value = '123';
			$form->elements['street']->value = '';
			$form->elements['city']->value = 'San Jose';
			$form->elements['state']->value = 'CA';
			$form->elements['zip']->value = '95131';
		}
		$form->fieldset('submit');
		$form->submit('submit', 'Pay now')->attribute('style', 'width: 100px; height: 40px;');
		try {
			if (Auth::getInstance()->hasIdentity()) {
				$user = Auth::getInstance()->getIdentity();
				//$form->elements['customerCustomer']->value = $user['name'];
                $shipData=$this->man->getPrimary($user['id']);
                $userData=$this->man->selectUser($user['id']);
//                system::dump($shipData['street']);exit();
                $form->elements['customerCustomer']->value = $shipData[0]['name1'].' '.$shipData[0]['name2'];
				$form->elements['customerEmail']->value = $userData['email'];
                $form->elements['customerAddress']->value = $shipData[0]['street'];
                $form->elements['customerCity']->value = $shipData[0]['city'];
                $form->elements['customerState']->value = $shipData[0]['state'];
                $form->elements['customerZip']->value = $shipData[0]['postal'];
                $form->elements['customerPhone']->value = $shipData[0]['phone'];
			}
		} catch (Exception $e) {
		}
		$cart = Cart::getInstance();
		$items = $cart->validateItems();
		if (count($items)) {
			if ($cart->isDigital($items)) {
				$this->delivery = false;
				$_SESSION['cartDelivery'] = false;
				$form->isDigital = true;
				unset($form->elements['State']);
				unset($form->elements['Zip']);
				unset($form->elements['City']);
				unset($form->elements['Address']);
			} else {
				$form->isDigital = false;
			}
			$this->template->content->form = new View('payment/creditcard-form', array('form' => $form));
			if (Request::$method == 'POST') {
				if ($form->validate()) {
					$items = $cart->validateItems();
					$values = $form->getValues();
					$values['acct'] = str_ireplace('-', '', $values['acct']);
					$values['expDate'] = $values['expMonth'] . $values['expYear'];
					$values['paymentAction'] = 'sale';
					$values['countryCode']   = 'US';
					$values['currencyCode']  = 'USD';
					$values['amt'] = $cart->getAmount($items, $this->delivery, $this->discount);
					$response = Paypal::getInstance()->request('DoDirectPayment', $values);
					if (isset($response['ack']) ? (strtolower($response['ack']) == 'success' || strtolower($response['ack']) == 'successwithwarning') : false) {
							$msg =  '';
							$msg .= 'Thank you for order!' . "\n\n";
							$msg .= 'You buy this items:' . "\n";
							foreach ($_SESSION['cart']['shop'] as $mailItems)
								{
									$msg .= 'Item: '.$mailItems['name'].',  Price: $'.$mailItems['price']."\n";
									isset($totalPrice)?$totalPrice+=$mailItems['price']:$totalPrice=$mailItems['price'];
								}
							$msg .= 'Total price: $' .$totalPrice. "\n";
						Mailer::sendMail($form->elements['customerEmail']->value, 'Message from ' . $_SERVER['HTTP_HOST'], $msg, $this->settings['title'].'<noreply@'.$_SERVER['HTTP_HOST'].'>');
						$this->flushSession();
						$order = array();
						$order['items'] = $items;
						$customerValues = array();
						foreach ($values as $k => $v) {
							if (substr($k, 0, 8) == 'customer') {
								$customerValues[strtolower(substr($k, 8, 1)) . substr($k, 9)] = $v;
							}
						}
						$orderValues['paypalMethod'] = 'DoDirectPayment';
						$orderValues['paypalAck'] = $response['ack'];
						$orderValues['paypalCorrelationId'] = $response['correlationid'];
						$orderValues['paypalTimestamp'] = $response['timestamp'];
						$orderValues['dateTimePaid'] = date('Y-m-d h:i');
						$order['order'] = $orderValues;
						$order['order']['delivery'] = $this->delivery;
						$order['order']['discount'] = $this->discount;
						$order['customer'] = $customerValues;
						$orderId = $cart->createOrder($order);
						if ($order = $this->model->getOrder($orderId)) {
							$cart->setPaid($orderId);
							$this->response->redirect(Request::$controller . 'success/' . $order['token'] . '/');
						}
					} else {
						$errors = '';
						foreach ($response as $k => $v) {
							if (preg_match_all('/^l_shortmessage(\d+)$/i', $k, $matches, PREG_SET_ORDER)) {
								if ($response['l_shortmessage' . $matches[0][1]] != 'Invalid Parameter') {
									$errors .= View::factory('payment/error', array('title' => $response['l_shortmessage' . $matches[0][1]], 'message' => $response['l_longmessage' . $matches[0][1]]));
//									var_dump($errors);
								}
							}
						}
						if (!isset($response['ack'])) {
							$this->template->content->errors = 'Can\'t connect to processing center';
						} else {
							$this->template->content->errors = $errors;
						}
					}
				}
			}
		} else {
			$this->template->content = new View('cart/message');
			$this->template->content->title = 'Shopping cart.';
			$this->template->content->message = 'Your shopping cart is empty.';
		}
	}


	public function actionGoPayPal()
	{

		$cart = Cart::getInstance();
		$items = $cart->validateItems();
		if (Cart::getInstance()->isDigital($items)) {
			$this->delivery = false;
		}
		$values['amt'] = $cart->getAmount($items, $this->delivery, $this->discount);
		$values['ReturnUrl'] = Url::site(Request::$controller . 'paypal/');
		$values['CancelUrl'] = Url::site(Request::$controller . 'checkout/');
		if (!$this->settings['isSandbox']) {
			$values['ReturnUrl'] = Url::site(Request::$controller . 'paypal/', 'https');
			$values['CancelUrl'] = Url::site(Request::$controller . 'checkout/', 'https');
		}
		$values['PaymentAction'] = 'Sale';
		$values['CurrencyCode'] = 'USD';
		$response = Paypal::getInstance()->request('SetExpressCheckout', $values);
		//system::dump($response);exit();
		if (isset($response['ack']) ? (strtolower($response['ack']) == 'success' || strtolower($response['ack']) == 'successwithwarning') : false) {
			if (isset($response['token'])) {
				$url = Paypal::getInstance()->setExpressCheckoutUrl($response['token']);
				$this->response->redirect($url);
			}
		} else {
			$this->template->title = 'Error occured while set up paypal payment';
			$this->template->content = new View('payment/result-error');
			$errors = array();
			foreach ($response as $k => $v) {
				if (preg_match_all('/^l_shortmessage(\d+)$/i', $k, $matches, PREG_SET_ORDER)) {
					if ($response['l_shortmessage' . $matches[0][1]] != 'Invalid Parameter') {
						$errors[] = View::factory('payment/error', array('title' => $response['l_shortmessage' . $matches[0][1]], 'message' => $response['l_longmessage' . $matches[0][1]]));
					}
				}
			}
			if (!isset($response['ack'])) {
				$this->template->content->errors = array(0 => 'Can\'t connect to processing center');
			} else {
				$this->template->content->errors = $errors;
			}
		}
	}

	public function actionPayPal()
	{
		if (isset($_GET['token'])) {
			$token = $_GET['token'];
		} else {
			throw new ForbiddenException();
		}
		$values['token'] = $token;
		$response = Paypal::getInstance()->request('GetExpressCheckoutDetails', $values);
		if (isset($response['ack']) ? (strtolower($response['ack']) == 'success' || strtolower($response['ack']) == 'successwithwarning') : false) {
			$_SESSION['paypalResponse'] = $response;
			$this->response->redirect(Request::$controller . 'paypaldetails/');
		} else {
			$this->template->content = new View('payment/result-error');
			$errors = array();
			foreach ($response as $k => $v) {
				if (preg_match_all('/^l_shortmessage(\d+)$/i', $k, $matches, PREG_SET_ORDER)) {
					if ($response['l_shortmessage' . $matches[0][1]] != 'Invalid Parameter') {
						$errors[] = View::factory('payment/error', array('title' => $response['l_shortmessage' . $matches[0][1]], 'message' => $response['l_longmessage' . $matches[0][1]]));
					}
				}
			}
			if (!isset($response['ack'])) {
				$this->template->content->errors = array(0 => 'Can\'t connect to processing center');
			} else {
				$this->template->content->errors = $errors;
			}
		}
	}

	private function flushSession()
	{
		unset($_SESSION['cart']);
		unset($_SESSION['cartDelivery']);
		unset($_SESSION['cartDiscount']);
		unset($_SESSION['paypalResponse']);
	}

	public function actionPayPalDetails()
	{

		if (!isset($_SESSION['paypalResponse'])) {
			throw new ForbiddenException();
		}
		$this->template->title = 'Payment with PayPal';
		$this->template->content = new View('payment/paypal-form');
		$this->addStyle('/styles/autoform.css');
		$form = new Form('payment');
		$form->labelWidth = '150px';
		$fullName = (isset($_SESSION['paypalResponse']['firstname']) ? $_SESSION['paypalResponse']['firstname'] : '') . ' ' . (isset($_SESSION['paypalResponse']['firstname']) ? $_SESSION['paypalResponse']['lastname'] : '');
		$fullName = trim($fullName);
		$form->text('customerCustomer', 'Full name', $fullName)->rule('required')->attribute('size', 40);
		$form->text('customerEmail', 'Email', $_SESSION['paypalResponse']['email'])->rule('required')->rule('email')->attribute('size', 40);
		$form->select('customerState', array_merge(array('' => ''), Text::$states), 'State', (isset($_SESSION['paypalResponse']['shiptostate']) ? $_SESSION['paypalResponse']['shiptostate'] : ''))->rule('required');
		$form->text('customerZip', 'ZIP-code', (isset($_SESSION['paypalResponse']['shiptozip']) ? $_SESSION['paypalResponse']['shiptozip'] : ''))->rule('required')->attribute('size', 10);
		$form->text('customerCity', 'City', (isset($_SESSION['paypalResponse']['shiptocity']) ? $_SESSION['paypalResponse']['shiptocity'] : ''))->rule('required')->attribute('size', 40);
		$form->text('customerAddress', 'Address', (isset($_SESSION['paypalResponse']['shiptostreet']) ? $_SESSION['paypalResponse']['shiptostreet'] : ''))->rule('required')->attribute('size', 40);
		$form->text('customerPhone', 'Phone')->attribute('size', 40);
		$form->textarea('customerComment', 'Comments')->attribute('cols', 30)->attribute('rows', 10);
		$form->submit('submit', 'Pay now')->attribute('style', 'width: 100px; height: 40px;');
		$cart = Cart::getInstance();
		$items = $cart->validateItems();
		if (count($items)) {
			if (Cart::getInstance()->isDigital($items)) {
				$this->delivery = false;
				$_SESSION['cartDelivery'] = false;
				$form->isDigital = true;
				unset($form->elements['State']);
				unset($form->elements['Zip']);
				unset($form->elements['City']);
				unset($form->elements['Address']);
			} else {
				$form->isDigital = false;
			}
			$this->template->content->form = $form;
			if (Request::$method == 'POST') {
				if ($form->validate()) {
					$values = $form->getValues();
					$delivery = (isset($_SESSION['cartDelivery']) ? $_SESSION['cartDelivery'] : false);
					$discount = (isset($_SESSION['cartDiscount']) ? $_SESSION['cartDiscount'] : 0);
					$values['amt'] = $cart->getAmount($items, $this->delivery, $this->discount);
					$values['token'] = isset($_SESSION['paypalResponse']['token']) ? $_SESSION['paypalResponse']['token'] : '';;
					$values['payerId'] = isset($_SESSION['paypalResponse']['payerid']) ? $_SESSION['paypalResponse']['payerid'] : '';
					$values['paymentAction'] = 'Sale';
					$values['currencyCode'] = 'USD';
					$response = Paypal::getInstance()->request('DoExpressCheckoutPayment', $values);
					if (isset($response['ack']) ? (strtolower($response['ack']) == 'success' || strtolower($response['ack']) == 'successwithwarning') : false) {
						$order = array();
						$order['items'] = $items;
						$customerValues = array();
						foreach ($values as $k => $v) {
							if (substr($k, 0, 8) == 'customer') {
								$customerValues[strtolower(substr($k, 8, 1)) . substr($k, 9)] = $v;
							}
						}
						$orderValues['paypalMethod'] = 'DoExpressCheckoutPayment';
						$orderValues['paypalAck'] = $response['ack'];
						$orderValues['paypalCorrelationId'] = $response['correlationid'];
						$orderValues['paypalTimestamp'] = $response['timestamp'];
						$orderValues['dateTimePaid'] = date('Y-m-d h:i');
						$orderValues['paypalEmail'] = $_SESSION['paypalResponse']['email'];
						$order['order'] = $orderValues;
						$order['order']['delivery'] = $this->delivery;
						$order['order']['discount'] = $this->discount;
						$order['customer'] = $customerValues;
						if ($orderId = $cart->createOrder($order)) {
							$cart->setPaid($orderId);
							$this->flushSession();
						}
						if ($order = $this->model->getOrder($orderId)) {
							$this->response->redirect(Request::$controller . 'success/' . $order['token'] . '/');
						}
					} else {
						$this->template->content = new View('payment/result-error');
						$errors = array();
						foreach ($response as $k => $v) {
							if (preg_match_all('/^l_shortmessage(\d+)$/i', $k, $matches, PREG_SET_ORDER)) {
								if ($response['l_shortmessage' . $matches[0][1]] != 'Invalid Parameter') {
									$errors[] = View::factory('payment/error', array('title' => $response['l_shortmessage' . $matches[0][1]], 'message' => $response['l_longmessage' . $matches[0][1]]));
								}
							}
						}
						if (!isset($response['ack'])) {
							$this->template->content->errors = array(0 => 'Can\'t connect to processing center');
						} else {
							$this->template->content->errors = $errors;
						}
					}
				}
			}
		}
	}

	public function actionSuccess($token)
	{
		$this->template->title = 'You have successfully paid for your order!';
		$this->template->content = new View('payment/result-success');
		$this->template->content->token = $token;
		$this->addStyle('/styles/autoform.css');
                
                if(isset($_SESSION['identity']['bonus_new_amount']))
                {
                    $amount = $_SESSION['identity']['bonus_new_amount'];
                    $id = $_SESSION['identity']['id'];
                    $this->manager->updateAccountBonusAmount($amount,$id);
                }
	}
        
//        public function actionTakebonus()
//        {
//            $this->autoRender = FALSE;
//
//            $account_bonus =  $this->manager->getBonusAmount($_SESSION['identity']['id']);
//            $bonus_new_amount = floor(trim($_POST['bonus_new']));
//
//
//            if((int)$account_bonus < (int)$bonus_new_amount){
//                $response['error']['message'] = 'Your bonus amount is too small';
//                $response['error']['amount'] = $account_bonus;
//            }
//            elseif((int)$bonus_new_amount < 0 || !is_numeric($bonus_new_amount)){
//                $response['error']['message'] = 'Type a positive number!';
//            }
//            else
//            {
//                $response['success']['acc_bonus'] = $account_bonus;
//                $response['success']['bonus_new'] = $_POST['bonus_new'];
//                $response['success']['acc_amount_new'] = (int)$account_bonus - (int)$bonus_new_amount;
//                $_SESSION['identity']['bonus_new_amount'] = $bonus_new_amount;
//            }
//
//
//
//            $this->response->setHeader('Content-Type', 'application/json');
//            $this->response->body = json_encode($response);
//        }

}
